﻿using Abp.Application.Services.Dto;
using Batman.Cms.Core.Controllers;
using Batman.Cms.Core.Models.Mvc;
using Batman.Jianbei.Forum.Controllers.Dicts.Filters;
using Batman.Jianbei.Forum.Controllers.Dicts.Input;
using Batman.Jianbei.Forum.Controllers.Dicts.Inputs;
using Batman.Jianbei.Forum.Core.Domains.Dicts;
using Batman.Jianbei.Forum.Services.Dicts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Omu.ValueInjecter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Jianbei.Forum.Controllers.Dicts
{
    [Authorize]
    public class PumpModelController : BatmanController<PumpModel>
    {
        /// <summary>
        /// 新建胰岛素泵品牌
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IActionResult Create(PumpModelCreateInput model)
        {
            var result = BaseManager.Excute(repo =>
            {
                var exists = repo.GetAll().AsNoTracking().Any(t => t.Name == model.Name && t.PumpBrandId == model.PumpBrandId);
                if (exists) return new ResponseBase(false, $"型号已存在:{model.Name}");

                var insulinPumpModelNew = new PumpModel();

                insulinPumpModelNew.InjectFrom(model);

                insulinPumpModelNew.CreateAt = DateTime.Now;
                insulinPumpModelNew.CreateBy = User.GetUserId();

                repo.Insert(insulinPumpModelNew);

                return new ResponseBase(true) { Success = true };
            });

            return Json(result);
        }

        /// <summary>
        /// 修改胰岛素泵品牌
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IActionResult Update(PumpModelUpdateInput model)
        {
            var query = Reader.Repository.GetAll().AsNoTracking();
            var pumpModel = query.FirstOrDefault(t => t.Id == model.Id);

            if (pumpModel == null)
                return Json(new ResponseBase(false, "型号不存在,无法更新保存"));

            pumpModel.InjectFrom(model);

            var result = BaseManager.Excute(repo =>
            {
                repo.Update(pumpModel);
                return new ResponseBase(true);
            });

            return Json(result);
        }

        /// <summary>
        /// 获取胰岛素泵型号列表
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> GetPumpModels(PagedResultRequestDto page, PumpModelFilter filter)
        {
            var query = Reader.Repository.GetAll().AsNoTracking().Include(t => t.PumpBrand).AsQueryable();
            if (!string.IsNullOrEmpty(filter.Name))
                query = query.Where(t => t.Name.Contains(filter.Name));
            if (!string.IsNullOrEmpty(filter.PumpId))
                query = query.Where(t => t.PumpBrandId == filter.PumpId);

            var total = await query.CountAsync();
            var items = await query.OrderByDescending(t => t.CreateAt).Skip(page.SkipCount).Take(page.MaxResultCount).ToListAsync();


            var result = new PagedResultDto<PumpModel>(total, items);
            return Json(result);
        }

        /// <summary>
        /// 获取胰岛素泵型号
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult GetPumpModel(string id)
        {
            var query = Reader.Repository.GetAll().AsNoTracking();

            var pumpModel = query.Where(t => t.Id == id).FirstOrDefault();

            if (pumpModel == null) return Json(new ResponseBase(false, "未知型号"));

            return Json(new ResponseBase(true) { Result = pumpModel });
        }

        public PumpModelManager PumpModelManager { get; set; }

        /// <summary>
        /// 删除型号
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public IActionResult Delete(List<string> ids)
        {
            if (ids == null) return Json(new ResponseBase(false, "没有指定要删除的胰岛素泵型号"));

            var result = BaseManager.Excute(repo =>
            {
                var pumpModels = repo.GetAll().AsNoTracking().Where(t => ids.Contains(t.Id)).ToList();

                foreach (var pumpModel in pumpModels)
                {
                    var canDelete = PumpModelManager.CanDelete(pumpModel.Id);
                    if (!canDelete) return new ResponseBase(false, $"请先删除相关的胰岛素泵销售信息,型号:{pumpModel.Name}");
                }
                repo.Delete(t => ids.Contains(t.Id));

                return new ResponseBase(true);
            });

            return Json(result);
        }
    }
}
